<template>
    <div class="contractDetail">
        <el-card style="margin-bottom: 20px;" v-hasPermi="['supplier:basics:edit']">
            <template #header>
                <div class="card_title">基础信息</div>
            </template>
            <el-form ref="supplierAddProductsFormRef" :model="form" style="width: 100%" :inline="true" :rules="rules"
                label-width="130px" scroll-to-error>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="供应商" prop="supplierName">
                            <el-input v-model="form.supplierName" placeholder="请输入" clearable style="width: 200px;"
                                maxlength="20" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商家类型" prop="supplierType">
                            <el-select v-model="form.supplierType" placeholder="请选择" clearable style="width: 200px;">
                                <el-option v-for="dict in hm_supplier_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="别名" prop="aliasName">
                            <el-input v-model="form.aliasName" placeholder="请输入" clearable style="width: 200px;"
                                maxlength="20" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="营业执照" prop="businessImage">
                            <ImageUploadDrags v-model="form.businessImage" :limit="1"
                                :fileType="['png', 'jpg', 'jpeg', 'pdf']" size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="营业执照有效期" prop="businessDate">
                            <el-select v-model="form.businessDate" placeholder="请选择" clearable style="width: 200px;">
                                <el-option v-for="dict in businessDateList" :key="dict.label" :label="dict.label"
                                    :value="dict.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="营业执照所在地" prop="businessAddr">
                            <el-cascader v-model="form.businessAddr" :options="options" :props="props"
                                style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="联系人" prop="contactName">
                            <el-input v-model="form.contactName" placeholder="请输入" maxlength="10" clearable
                                style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系电话" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入" clearable style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="详细地址" prop="address">
                            <el-input v-model="form.address" placeholder="请输入" clearable style="width: 200px;"
                                @input="(e: any) => { forbidRule(e, 'address', 'emoji') }" maxlength="100" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="厂家地址" prop="addr">
                            <el-cascader v-model="form.addr" :options="options" :props="props" style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="统一社会信用代码" prop="companyCode">
                            <el-input v-model="form.companyCode" placeholder="请输入" clearable style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="false">
                        <el-form-item label="对接群名" prop="groupName">
                            <el-input v-model="form.groupName" placeholder="请输入" clearable style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="店铺类型" prop="storeType">
                            <el-input v-model="form.storeType" placeholder="请输入" clearable style="width: 200px;"
                                maxlength="50" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="店铺id" prop="storeId">
                            <el-input v-model="form.storeId" placeholder="请输入" clearable style="width: 200px;"
                                maxlength="50" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="店铺评分" prop="storeGrade">
                            <el-input v-model="form.storeGrade" placeholder="请输入" clearable style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <div class="details_line">
                            <div class="label">其他资质</div>
                            <div class="value">
                                <ImageUploadDrags v-model="form.otherImage" :limit="5"
                                    :fileType="['png', 'jpg', 'jpeg', 'pdf']" size="small" />
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="editButtons">
                    <el-button @click="cancel">取消</el-button>
                    <el-button v-loading="supplierSaveLoading" type="primary"
                        @click="supplierSave(supplierAddProductsFormRef)">保存</el-button>
                </div>
            </template>
        </el-card>
        <el-card style="margin-bottom: 20px;" v-hasPermi="['main:company:edit']">
            <template #header>
                <div class="card_title">
                    <span>主体信息</span>
                    <el-button type="primary"
                        @click="getElMessageBox('主体公司名称', '添加', '请输入主体公司名称', 0, 'add')">添加主体</el-button>
                </div>
            </template>
            <div class="company">
                <div class="company_item" v-for="(item, index) in dataSource" :key="index">
                    <div class="company_item_title">主体{{ index + 1 }}</div>
                    <el-tree style="width: 600px" :data="item" node-key="id" default-expand-all
                        :expand-on-click-node="false" :props="defaultProps">
                        <template #default="{ node, data }">
                            <div class="company_box">
                                <div class="company_box_name">
                                    <img class="company_box_img"
                                        :src="node.level === 1 ? icon_zhutigongsi : node.level === 2 ? icon_zhutidianpu : icon_dianpu"
                                        alt="">
                                    <span
                                        :class="{ company_box_text: true, fontWeight900: node.level === 1, fontWeight500: node.level === 2 }"
                                        v-if="node.level !== 3">{{
                                            node.label
                                        }}</span>
                                    <span class="company_box_text" v-else>{{ node.label }}({{ node.data.storeId
                                        }})</span>
                                </div>
                                <div class="company_box_button">
                                    <el-button v-if="node.level !== 3" type="primary" link icon="Plus"
                                        @click="operation(node, data, index, 'add')" />
                                    <el-button type="primary" link icon="Setting"
                                        @click="operation(node, data, index, 'edit')" />
                                    <el-button type="danger" link icon="Delete"
                                        @click="operation(node, data, index, 'delete')" />
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </div>
            <template #footer v-if="dataSource.length">
                <div class="editButtons">
                    <el-button @click="cancel">取消</el-button>
                    <el-button v-loading="supplierSaveLoading" type="primary"
                        @click="supplierSave(supplierAddProductsFormRef)">保存</el-button>
                </div>
            </template>
        </el-card>
        <el-card style="margin-bottom: 20px;">
            <template #header>
                <div class="card_title">合同信息</div>
            </template>
            <el-table :data="form.contractList" style="width: 100%;height: auto;min-height: 200px;">
                <el-table-column label="合同类型" prop="contractType" show-overflow-tooltip />
                <el-table-column label="合同名称" prop="fileName" show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.fileName }}
                    </template>
                </el-table-column>
                <el-table-column label="签订时间" prop="createTime" show-overflow-tooltip />
                <el-table-column label="上传时间" prop="signTime" show-overflow-tooltip />
                <el-table-column label="操作人" prop="czr" show-overflow-tooltip />
                <el-table-column label="备注" prop="bz" show-overflow-tooltip />
                <el-table-column label="保证金金额" prop="bzjje" show-overflow-tooltip />
                <el-table-column label="交保证金时间" prop="bzjtime" show-overflow-tooltip />
                <el-table-column label="是否完成" prop="sfwc" show-overflow-tooltip />
                <el-table-column label="对账专用区" prop="dzzyq" show-overflow-tooltip />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button v-hasPermi="['supplier:contract:edit']" link type="primary"
                            @click="uploadContractFile(scope.row.id)">编辑</el-button>
                        <el-button v-hasPermi="['supplier:contract:preview']" link type="primary"
                            @click="preview(scope.row.contractFile)">预览</el-button>
                        <el-button v-hasPermi="['supplier:contract:download']" link type="primary"
                            @click="dowload(scope.row.contractFile)">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <div class="contract_div">
                <div class="contract_item">
                    <div class="contract_item_font">供销合同</div>
                    <div class="contract_item_name">{{ contractSellName }}</div>
                    <div v-if="contractSellName !== '-'" class="button_list">
                        <div class="preview buttons" @click="preview(contractSellUrl)">预览</div>
                        <div class="dowload buttons" @click="dowload(contractSellOssId)">下载</div>
                    </div>
                </div>
                <div class="contract_item">
                    <div class="contract_item_font">破价合同</div>
                    <div class="contract_item_name">{{ contractDiscountName }}</div>
                    <div v-if="contractDiscountName !== '-'" class="button_list">
                        <div class="preview buttons" @click="preview(contractDiscountUrl)">预览</div>
                        <div class="dowload buttons" @click="dowload(contractDiscountOssId)">下载</div>
                    </div>
                </div>
                <div class="contract_item">
                    <div class="contract_item_font">保证金协议</div>
                    <div class="contract_item_name">{{ marginName }}</div>
                    <div v-if="marginName !== '-'" class="button_list">
                        <div class="preview buttons" @click="preview(marginNameUrl)">预览</div>
                        <div class="dowload buttons" @click="dowload(marginNameUrlssId)">下载</div>
                    </div>
                </div>
                <div class="contract_item">
                    <div class="contract_item_font">补充协议</div>
                    <div class="contract_item_name">{{ supplementaryName }}</div>
                    <div v-if="supplementaryName !== '-'" class="button_list">
                        <div class="preview buttons" @click="preview(supplementaryUrl)">预览</div>
                        <div class="dowload buttons" @click="dowload(supplementaryOssId)">下载</div>
                    </div>
                </div>
                <div class="contract_item">
                    <div class="contract_item_font">包销合同</div>
                    <div class="contract_item_name">{{ underwriteName }}</div>
                    <div v-if="underwriteName !== '-'" class="button_list">
                        <div class="preview buttons" @click="preview(underwriteUrl)">预览</div>
                        <div class="dowload buttons" @click="dowload(underwriteOssId)">下载</div>
                    </div>
                </div>
            </div> -->
        </el-card>
        <!-- 研发部登录品牌隐藏 -->
        <el-card v-hasPermi="['supplier:brand:look']">
            <template #header>
                <div class="card_title">
                    <spam>品牌信息</spam>
                    <el-button v-hasPermi="['supplier:brand:add']" type="primary" @click="addBrands"
                        :disabled="!query.supplierId">添加品牌</el-button>
                </div>
            </template>
            <el-table v-loading="loading" :data="brandList" style="width: 100%;height: auto;min-height: 200px;">
                <el-table-column label="品牌名称" align="center" prop="brandName" />
                <el-table-column label="品牌商标注册证" align="center" prop="brandImage">
                    <template #default="scope">
                        <image-preview :src="scope.row.brandImage" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="商标授权使用证明" align="center" prop="usageImage">
                    <template #default="scope">
                        <image-preview :src="scope.row.usageImage" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="使用授权品类" align="center" prop="usages">
                    <template #default="scope">
                        {{ handleFilterMultiple(scope.row.usages, hm_trademark) }}
                    </template>
                </el-table-column>
                <el-table-column label="店铺销售授权" align="center" prop="sellImage">
                    <template #default="scope">
                        <image-preview :src="scope.row.sellImage" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="销售授权品类" align="center" prop="sells">
                    <template #default="scope">
                        {{ handleFilterMultiple(scope.row.sells, hm_trademark) }}
                    </template>
                </el-table-column>
                <el-table-column label="其他资质补充" align="center" prop="otherImage">
                    <template #default="scope">
                        <image-preview :src="scope.row.otherImage" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="联名款或其他授权文件" align="center" prop="jointlyImage">
                    <template #default="scope">
                        <image-preview :src="scope.row.jointlyImage" :width="50" :height="50" />
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-drawer class="hm-drawer" :title="dialog.title" v-model="dialog.visible" size="40%" direction="rtl"
            :close-on-click-modal="false" @close="reset">
            <el-form ref="brandFormRef" :model="formBrand" :rules="brandFormRefRules" label-width="160px">
                <el-form-item label="品牌名称" prop="brandName">
                    <el-input v-model="formBrand.brandName" placeholder="请输入品牌名称" clearable maxlength="50" />
                </el-form-item>
                <el-form-item label="品牌商标注册证" label-width="160px" style="color:red" prop="brandImage">
                    <ImageUploadDrags v-model="formBrand.brandImage" :limit="1"
                        :fileType="['png', 'jpg', 'jpeg', 'pdf']" size="small" />
                </el-form-item>
                <el-form-item label="商标授权使用证明" label-width="160px" prop="usageImage">
                    <ImageUploadDrags v-model="formBrand.usageImage" :limit="1"
                        :fileType="['png', 'jpg', 'jpeg', 'pdf']" size="small" />
                </el-form-item>
                <el-form-item label="使用授权品类" prop="usages">
                    <el-select multiple v-model="formBrand.usages" placeholder="请选择授权品类" clearable>
                        <el-option v-for="dict in hm_trademark" :key="dict.label" :label="dict.label"
                            :value="dict.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="店铺销售授权" label-width="160px" prop="sellImage">
                    <ImageUploadDrags v-model="formBrand.sellImage" :limit="1" :fileType="['png', 'jpg', 'jpeg', 'pdf']"
                        size="small" />
                </el-form-item>
                <el-form-item label="销售授权品类" prop="sells">
                    <el-select multiple v-model="formBrand.sells" placeholder="请选择授权品类" clearable>
                        <el-option v-for="dict in hm_trademark" :key="dict.label" :label="dict.label"
                            :value="dict.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="其他资质补充" label-width="160px" prop="otherImage">
                    <ImageUploadDrags v-model="formBrand.otherImage" :limit="1"
                        :fileType="['png', 'jpg', 'jpeg', 'pdf']" size="small" />
                </el-form-item>
                <el-form-item label="联名款或其他授权文件" label-width="160px" prop="jointlyImage">
                    <ImageUploadDrags v-model="formBrand.jointlyImage" :limit="1"
                        :fileType="['png', 'jpg', 'jpeg', 'pdf']" size="small" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm(brandFormRef)">确 定</el-button>
                    <el-button @click="cancelBrand">取 消</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog v-model="companyDialogValue.show" :title="companyDialogValue.title" width="500"
            :before-close="handleClose">
            <el-form ref="companyDialogForm" :model="ruleForm" :rules="companyRules" label-width="80px">
                <el-form-item label="店铺名称" prop="name">
                    <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="店铺id" prop="storeId">
                    <el-input v-model="ruleForm.storeId" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="companySubmitForm(companyDialogForm)">确定</el-button>
                    <el-button @click="resetForm(companyDialogForm)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <contractFile @doClose="contractFileClose" :contractFileData="contractFileData"
            :contractFileVisible="contractFileVisible"></contractFile>
    </div>
</template>
<script setup name="contractDetail" lang="ts">
const { proxy } = getCurrentInstance() as any;
import { BrandVO } from '@/api/system/brand/types';
import { hmSupplierList, hmSupplierPut, hmSupplierAdd } from '@/api/group/supplier/index';
import { getHmContract } from '@/api/system/hmContract';
import { SupplierDetail } from '@/api/group/supplier/types';
import jsonData from './address.json';
import { handleFilterMultiple } from '@/utils/handleFilters';
import { generateUUID } from '@/utils/index';
import type { FormInstance } from 'element-plus';
import { listBrand, getBrand, updateBrand, addBrand } from '@/api/system/brand';
import { ElMessage, ElMessageBox } from 'element-plus'
import contractFile from '@/views/group/contract/compoments/contractFile.vue';

import icon_zhutigongsi from '@/assets/images/icon_zhutigongsi.png'
import icon_zhutidianpu from '@/assets/images/icon_zhutidianpu.png'
import icon_dianpu from '@/assets/images/icon_dianpu.png'

const { hm_supplier_type } = toRefs<any>(proxy?.useDict('hm_supplier_type'));
const { hm_trademark } = toRefs<any>(proxy?.useDict('hm_trademark'));
/** 营业执照有效期 */
const businessDateList = ref([
    { label: '1年', value: '1' },
    { label: '10年', value: '10' },
    { label: '20年', value: '20' },
    { label: '长期', value: '0' }
]);
// 地址数据
const options = jsonData;

const route = useRoute();
const router = useRouter();
const { query } = route;
const detailInfo = ref<SupplierDetail>({});
const editFlag = ref(false);
const supplierSaveLoading = ref(false);
const tableData = ref([])
const form = ref<SupplierDetail>({
    id: undefined,
    supplierName: undefined,
    aliasName: undefined,
    groupName: undefined,
    companyCode: undefined,
    businessImage: undefined,
    businessDate: undefined,
    businessAddr: undefined,
    addr: undefined,
    address: '',

    supplierType: undefined,
    contactName: undefined,
    phone: undefined,
    storeId: undefined,
    storeType: undefined,
    storeGrade: undefined
});
const supplierAddProductsFormRef = ref<FormInstance>();
const contractFileVisible = ref(false)
const contractFileData = ref<any>()

const props = {
    label: 'value',
    value: 'value'
};

// 供销合同名称
const contractSellName = ref<string>('-');
const contractSellUrl = ref<string>('');
const contractSellOssId = ref<string | number>('');
// 破价合同名称
const contractDiscountName = ref<string>('-');
const contractDiscountUrl = ref<string>('');
const contractDiscountOssId = ref<string | number>('');
// 保证金协议名称
const marginName = ref<string>('-');
const marginNameUrl = ref<string>('');
const marginNameUrlssId = ref<string | number>('');
// 补充协议名称
const supplementaryName = ref<string>('-');
const supplementaryUrl = ref<string>('');
const supplementaryOssId = ref<string | number>('');
// 包销合同名称
const underwriteName = ref<string>('-');
const underwriteUrl = ref<string>('');
const underwriteOssId = ref<string | number>('');



// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        form.value[key] = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '');
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        form.value[key] = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '');
    }
};
const validatorCompanyCode = (rule: any, value: string, callback: any) => {
    if (value) {
        if (/^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/.test(value)) {
            callback();
        } else {
            callback(new Error('请输入正确的统一社会信用代码'));
        }
    } else {
        callback();
    }
};
// 联系人验证函数，只能输入中文跟·
const validatorContact = (rule: any, value: string, callback: any) => {
    if (/^[\u4e00-\u9fa5·]+$/.test(value)) {
        callback();
    } else {
        callback(new Error('请输入中文或点·'));
    }
};
// 店铺评分验证函数，0-100之间的整数，保留小数点后两位
const validatorStoreGrade = (rule: any, value: string, callback: any) => {
    if (value) {
        if (/^([0-9]{1,2}$)|(^[0-9]{1,2}\.[0-9]{1,2}$)|100$/.test(value)) {
            callback();
        } else {
            callback(new Error('0-100内整数，最大小数点后两位'));
        }
    } else {
        callback();
    }
};
const rules = ref({
    supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' }],
    aliasName: [{ required: true, message: '别名不能为空', trigger: 'blur' }],
    addr: [{ required: true, message: '请选择厂家地址', trigger: 'change' }],
    address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
    supplierType: [{ required: true, message: '请选择商家类型', trigger: 'change' }],
    contactName: [
        { required: true, message: '联系人不能为空', trigger: 'blur' },
        { validator: validatorContact, trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '联系电话不能为空', trigger: 'blur' },
        { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    companyCode: [{ required: false, validator: validatorCompanyCode, trigger: 'blur' }],
    storeGrade: [{ required: false, validator: validatorStoreGrade, trigger: 'blur' }]
});
const brandFormRefRules = ref({
    brandName: [
        {
            required: true,
            message: '品牌名称不能为空',
            trigger: 'blur'
        }
    ]
});
const brandList = ref<BrandVO[]>([]);
const loading = ref(false);

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});
const formBrand = ref({
    id: undefined,
    brandName: undefined,
    brandImage: undefined,
    usageImage: undefined,
    sellImage: undefined,
    otherImage: undefined,
    jointlyImage: undefined,
    remark: undefined,
    usageCategory: undefined,
    sellCategory: undefined,
    sells: <any>[],
    usages: <any>[]
});
const buttonLoading = ref(false);
const brandFormRef = ref<ElFormInstance>();

// 数结构props配置项
const defaultProps = {
    children: 'children',
    label: 'name'
}
// 主体存储数据 
const dataSource = ref<any>([])
// 主体编辑弹框配置项
const companyDialogValue = ref({
    show: false,
    title: '',
    dataId: '',
    dataIndex: 0
})
// 主体表单ref
const companyDialogForm = ref()
// 主体表单value值
const ruleForm = ref({
    name: '',
    storeId: ''
})
// 主体表单验证规则
const companyRules = reactive<any>({
    name: [
        { required: true, message: '请输入店铺名称', trigger: 'blur' },
    ],
    storeId: [
        { required: true, message: '请输入店铺id', trigger: 'blur' },
    ]
})

// 主体公司操作
const operation = (node: any, data: any, index: number, type: string) => {
    if (type === 'delete') {
        // 主体删除操作
        ElMessageBox.confirm(
            `确认删除${node.level === 1 ? '主体公司' : node.level === 2 ? '主体店铺' : '店铺小店'}${data.name}?`,
            '删除',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'error',
            }
        ).then(() => {
            // 判断主体层级
            if (node.level === 1) {
                // 如果点击一级层级，删除整个数组项
                dataSource.value.splice(index, 1)
            } else {
                // 二，三级删除，删除单个object对象
                const parent = node.parent
                const children: any = parent.data.children || parent.data
                const index = children.findIndex((d: any) => d.id === data.id)
                children.splice(index, 1)
                dataSource.value = [...dataSource.value]
            }
            ElMessage({
                type: 'success',
                message: '删除成功',
            });
        }).catch(() => { })
    } else if (type === 'edit') {
        // 主体修改操作
        if (node.level === 1) {
            // 点击一级修改，传入提示文字为主体公司
            getElMessageBox('主体公司名称', '编辑', '请输入主体公司名称', node.level, type, data)
        } else if (node.level === 2) {
            // 点击二级修改，传入提示文字为主体店铺
            getElMessageBox('主体店铺名称', '编辑', '请输入主体店铺名称', node.level, type, data)
        } else {
            // 点击三级修改，需要输入名称跟id，ElMessageBox组件不满足要求，使用对话框组件
            companyDialogValue.value = {
                show: true,
                title: '编辑',
                dataId: data.id,
                dataIndex: index
            }
            // 表单反显数据
            ruleForm.value = {
                name: data.name,
                storeId: data.storeId
            }
        }
    } else {
        // 主体修改操作，新增只能新增到三级
        if (node.level === 1) {
            // 根据点击的层级判断是否是添加主体店铺还是店铺小店，主要提示字体区分
            getElMessageBox('主体店铺名称', '添加', '请输入主体店铺名称', node.level, type, data)
        } else if (node.level === 2) {
            // 添加三级需要输入名称跟id，ElMessageBox组件不满足要求，使用对话框组件
            companyDialogValue.value = {
                show: true,
                title: '添加',
                dataId: data.id,
                dataIndex: index
            }
        }
    }
}
// 调用输入弹框操作
const getElMessageBox = (text: string, title: string, inputPlaceholder: string, level: number, type: string, data?: any) => {
    // text：弹框文本
    // title：弹框标题
    // inputPlaceholder：输入框提示文字
    // level：主体的层级
    // type：类型：新增(add)/编辑(edit)
    // data: 新增/编辑时传入的数据
    ElMessageBox.prompt(text, title, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValue: type === 'edit' ? data ? data.name : null : null,
        inputPlaceholder: inputPlaceholder,
        inputValidator: (value: any) => {
            if (!value) {
                return inputPlaceholder
            }
            return true
        }
    }).then(({ value }) => {
        if (type === 'add') {
            const obj = [{
                id: generateUUID(),
                name: value,
                children: [],
                type: level - 1
            }]
            if (level === 0) {
                // 增加主体公司
                dataSource.value.push(obj)
            } else {
                // 增加主体店铺
                data.children.push(obj[0]);
            }
            ElMessage({
                type: 'success',
                message: '添加成功',
            })
        } else if (type === 'edit') {
            data.name = value;
            ElMessage({
                type: 'success',
                message: '修改成功',
            });
        }
    }).catch(() => { })
}
// 三级主体店铺弹框关闭
const handleClose = (done: () => void) => {
    done()
}
// 三级主体店铺弹框确认
const companySubmitForm = async (formEl: any) => {
    if (!formEl) return
    await formEl.validate((valid: any, fields: any) => {
        if (valid) {
            if (companyDialogValue.value.title === '添加') {
                const obj = {
                    id: generateUUID(),
                    name: ruleForm.value.name,
                    storeId: ruleForm.value.storeId,
                    children: [],
                    type: 2
                }
                insertChildById(dataSource.value[companyDialogValue.value.dataIndex], companyDialogValue.value.dataId, obj, '添加')
                resetForm(formEl)
                ElMessage({
                    type: 'success',
                    message: '添加成功',
                })
            } else {
                insertChildById(dataSource.value[companyDialogValue.value.dataIndex], companyDialogValue.value.dataId, ruleForm.value, '修改')
                resetForm(formEl)
                ElMessage({
                    type: 'success',
                    message: '修改成功',
                });
            }
        }
    })
}
// 公用树结构查找数据后，添加与修改
const insertChildById = (tree: any, targetId: string, newChild: any, type: string) => {
    for (const node of tree) {
        if (node.id === targetId) {
            if (!node.children) {
                node.children = [];
            }
            if (type === '添加') {
                node.children.push(newChild);
            } else {
                node.name = newChild.name;
                node.storeId = newChild.storeId
            }
            return true;
        }
        if (node.children && insertChildById(node.children, targetId, newChild, type)) {
            return true;
        }
    }
    return false;
}
// 三级主体店铺弹框取消
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    companyDialogValue.value = {
        show: false,
        title: '',
        dataId: '',
        dataIndex: 0
    }
}


/** 取消修改供应商 */
const cancel = () => {
    proxy?.$tab.closePage(route).then(() => {
        router.go(-1)
    })
};
/** 保存修改供应商 */
const supplierSave = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            supplierSaveLoading.value = true;
            if (query.routerType === 'add') {
                const formCopy = JSON.parse(JSON.stringify(form.value));
                formCopy.addr = formCopy.addr ? (formCopy.addr as string[]).join('-') : '';
                formCopy.businessAddr = formCopy.businessAddr ? (formCopy.businessAddr as string[]).join('-') : '';
                try {
                    await hmSupplierAdd({ ...formCopy, supplierCompanys: dataSource.value });
                    supplierSaveLoading.value = false;
                    proxy?.$modal.msgSuccess('新增成功');
                    cancel()
                } catch (err) { } finally {
                    supplierSaveLoading.value = false;
                }
            } else {
                const formCopy = JSON.parse(JSON.stringify(form.value));
                formCopy.addr = formCopy.addr ? (formCopy.addr as string[]).join('-') : '';
                formCopy.businessAddr = formCopy.businessAddr ? (formCopy.businessAddr as string[]).join('-') : '';
                try {
                    await hmSupplierPut({ ...formCopy, supplierCompanys: dataSource.value });
                    supplierSaveLoading.value = false;
                    proxy?.$modal.msgSuccess('修改成功');
                    editFlag.value = false;
                    detailInfo.value = {};
                    cancel()
                } catch (err) { } finally {
                    supplierSaveLoading.value = false;
                }
            }
        } else {
            console.log('error submit!', fields);
        }
    });
};

/** 根据合同类型获取合同名称 */
const contractNameByType = async (type: string, row: any) => {
    if (row) {
        const rows = row.filter((item: any) => item.contractType == type);
        if (rows.length > 0) {
            if (type == '供销合同') {
                contractSellUrl.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
                contractSellOssId.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
            } else if (type == '破价合同') {
                contractDiscountUrl.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
                contractDiscountOssId.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
            } else if (type == '保证金协议') {
                marginNameUrl.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
                marginNameUrlssId.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
            } else if (type == '补充协议') {
                supplementaryUrl.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
                supplementaryOssId.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
            } else if (type == '包销合同') {
                underwriteUrl.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
                underwriteOssId.value = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile;
            }
            return rows[0].fileName;
        } else {
            return '-';
        }
    } else {
        return '-';
    }
};
/** 获取供应商详情 */
const supplierDetail = async () => {
    const res = await hmSupplierList({ id: query.supplierId });
    form.value = res.rows[0];
    form.value.businessAddr = form.value.businessAddr ? (form.value.businessAddr as string).split('-') : [];
    form.value.addr = (form.value.addr as string).split('-');
    contractSellName.value = await contractNameByType('供销合同', form.value.contractList);
    contractDiscountName.value = await contractNameByType('破价合同', form.value.contractList);
    marginName.value = await contractNameByType('保证金协议', form.value.contractList);
    supplementaryName.value = await contractNameByType('补充协议', form.value.contractList);
    underwriteName.value = await contractNameByType('包销合同', form.value.contractList);
};
/** 查询品牌列表 */
const getListBrand = async () => {
    loading.value = true;
    const resposne = await listBrand({ supplierId: query.supplierId as string });
    brandList.value = resposne.rows;
    loading.value = false;
}
/** 预览 */
const preview = (url: string) => {
    window.open(import.meta.env.VITE_APP_PREVIEW_URL + url, '_blank');
};
/** 下载 */
const dowload = (ossId: any) => {
    window.open(import.meta.env.VITE_APP_PIC_URL + ossId, '_blank');
};
/** 添加品牌 */
const addBrands = () => {
    dialog.visible = true;
    dialog.title = '添加品牌';
};
/** 修改品牌 */
const handleUpdate = async (row: BrandVO) => {
    dialog.visible = true;
    dialog.title = '修改品牌';
    reset();
    const res = await getBrand(row.id);
    Object.assign(formBrand.value, res.data);
    formBrand.value.sells = formBrand.value.sells ? formBrand.value.sells.split(',') : [];
    formBrand.value.usages = formBrand.value.usages ? formBrand.value.usages.split(',') : [];
};
/** 品牌确定 */
const submitForm = async (brandFormRef: FormInstance | undefined) => {
    if (!brandFormRef) return;
    await brandFormRef.validate(async (valid, fields) => {
        if (valid) {
            buttonLoading.value = true;
            const data = JSON.parse(JSON.stringify(formBrand.value));
            data.sells = data.sells.join(',');
            data.usages = data.usages.join(',');
            try {
                if (dialog.title == '修改品牌') {
                    await updateBrand(data);
                    proxy?.$modal.msgSuccess('修改品牌成功');
                } else {
                    data.supplierId = query.supplierId;
                    await addBrand(data);
                    proxy?.$modal.msgSuccess('新增品牌成功');
                }
                dialog.visible = false;
                buttonLoading.value = false;
                reset();
                getListBrand();
            } catch (err) {
                buttonLoading.value = false;
            }
        }
    });
};
/** 品牌取消 */
const cancelBrand = () => {
    reset();
    dialog.visible = false;
};
/** 品牌表单重置 */
const reset = () => {
    formBrand.value = {
        id: undefined,
        brandName: undefined,
        brandImage: undefined,
        usageImage: undefined,
        sellImage: undefined,
        otherImage: undefined,
        jointlyImage: undefined,
        remark: undefined,
        usageCategory: undefined,
        sellCategory: undefined,
        sells: [],
        usages: []
    };
    brandFormRef.value?.resetFields();
};
/** 我的意向关闭 */
const contractFileClose = () => {
    contractFileVisible.value = false;
    supplierDetail();
};
/** 上传合同 */
const uploadContractFile = async (id: string) => {
    const res = await getHmContract(id);
    contractFileVisible.value = true;
    contractFileData.value = res.data;
};
onMounted(() => {
    if (query.routerType === 'edit') {
        supplierDetail();
        getListBrand()
    }
});
</script>
<style scoped lang="scss">
.contractDetail {
    width: 100%;
    height: 100%;
    padding: 30px;
    box-sizing: border-box;

    .card_title {
        font-weight: 700;
        color: var(--el-text-color-regular);
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .details_line {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        width: 100%;

        .label {
            width: 130px;
            text-align: right;
            padding: 0 12px 0 0;
            color: var(--el-text-color-regular);
            box-sizing: border-box;
            font-size: var(--el-form-label-font-size);
            height: 32px;
            line-height: 32px;
            font-weight: 700;
        }

        .value {
            flex: 1;
            display: flex;
            word-break: break-all;
        }
    }

    .editButtons {
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }

    .company {
        width: 100%;
        padding: 0 0 20px 0;
        overflow-x: auto;
        display: flex;

        .company_item {
            border: 1px solid #ebeef5;
            padding: 10px;
            margin-right: 20px;

            .company_item_title {
                padding: 5px 10px 10px;
                border-bottom: 1px solid #ebeef5;
                font-size: 16px;
                color: var(--el-text-color-regular);
                font-weight: 700;
                margin-bottom: 10px;
            }
        }

        .company_box {
            flex: 1;
            min-width: 0;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .company_box_name {
                flex: 1;
                min-width: 0;
                display: flex;
                align-items: center;

                .company_box_img {
                    width: 15px;
                    height: 15px;
                    margin-right: 5px;
                }

                .company_box_text {
                    flex: 1;
                    min-width: 0;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    margin-right: 10px;

                }

                .fontWeight900 {
                    font-weight: 900;
                }

                .fontWeight500 {
                    font-weight: 600;
                }
            }

            .company_box_button {
                display: flex;
            }
        }
    }
}
</style>